<?php 
/**
 * register.php
 *
 * Registration management
 *
 * @author     Makai Lajos
 * @copyright  2015
 * @license    License.txt
 * @version    2.0
 * @link       http://opencart-api.com/product/opencart-restful-api-pro-v2-0/
 * @see        http://newapi2.opencart-api.com/demo/
 */
require_once(DIR_SYSTEM . 'engine/restcontroller.php');

class ControllerRestRegister extends RestController {

	public function registerCustomer($data) {

		$this->language->load('checkout/checkout');

		$this->load->model('account/customer');

		$json = array('success' => true);
		
		// Validate if customer is logged in.
		if ($this->customer->isLogged()) {
			$json['error']['warning']		= "用户已经登陆";	
			$json['success'] = false;
		} 


		// 貌似是购物车相关，不知道该不该留Validate minimum quantity requirments.			
		$products = $this->cart->getProducts();

		foreach ($products as $product) {
			$product_total = 0;

			foreach ($products as $product_2) {
				if ($product_2['product_id'] == $product['product_id']) {
					$product_total += $product_2['quantity'];
				}
			}		

			if ($product['minimum'] > $product_total) {
				//$json['redirect'] = $this->url->link('checkout/cart');
				$json['success'] = false;
				// $json['error']['minimum'] = "Product minimum > product total";
				$json['error']['warning'] = "Product minimum > product total";
				break;
			}				
		}

		if ($json['success']) {					
			//验证手机号码是否已经注册
			if (!preg_match('/^1[0-9]{10}$/', $data['telephone'])) {
				$json['error']['warning'] ="手机号码输入错误";
			}

            //验证用户是否已经注册
			$this->load->model('account/customer');
			$res=$this->model_account_customer->getCustomerByTelephone($data['telephone']);
			if($res){
				$json['error']['warning'] ="用户已经注册过了";
			}

			// 验证用户验证码
			// $this->load->model('account/smsmobile');
			// $res=$this->model_account_smsmobile->verifySmsCode($data['telephone'],$data['sms_code']);
   //          if(!$res){
   //          	$json['error']['warning'] ="验证码不匹配";
   //          }
			
           //验证密码是否正确
			if ((utf8_strlen($data['password']) < 6) || (utf8_strlen($data['password']) > 32)) {
				$json['error']['warning'] = "密码小于6位或者大于32位";
			}
			$data['email']=$data['telephone'];
			$data['fullname']=$data['telephone'];
            
            //验证推荐码是否存在
			if($data['recommended_code']){
				
				$this->load->model('account/user');
				$filter['recommended_code'] = $data['recommended_code'];
				$user_id=$this->model_account_user->getUser($filter);

				if($user_id){
					$data['user_id'] = $user_id;
                    $data['logcenter_id'] = $this->model_account_user->getDefaultLogcenter($user_id);
				}
				else{
					$json['error']['warning'] = "无此推荐码业务员";
				}

			}		
			
          //二次验证密码
			if (isset($data['confirm'])&&$data['confirm'] != $data['password'])  {
				$json['error']['confirm'] = $this->language->get('error_confirm');
				// $json['error']['warning'] = $this->language->get('error_confirm');
			}
        
        //是否同意注册协议
			/*if ($this->config->get('config_account_id')) {
				$this->load->model('catalog/information');

				$information_info = $this->model_catalog_information->getInformation($this->config->get('config_account_id'));

				if ($information_info && !isset($data['agree'])) {
					$json['error']['warning'] = sprintf($this->language->get('error_agree'), $information_info['title']);
				}
			}*/

			// Customer Group
			if (isset($data['customer_group_id']) && is_array($this->config->get('config_customer_group_display')) && in_array($data['customer_group_id'], $this->config->get('config_customer_group_display'))) {
				$customer_group_id = $data['customer_group_id'];
			} else {
				$customer_group_id = $this->config->get('config_customer_group_id');
			}

			// Custom field validation
			$this->load->model('account/custom_field');
            
			$custom_fields = $this->model_account_custom_field->getCustomFields($customer_group_id);

			foreach ($custom_fields as $custom_field) {
				if ($custom_field['required'] && empty($data['custom_field'][$custom_field['location']][$custom_field['custom_field_id']])) {
					$json['error']['custom_field' . $custom_field['custom_field_id']] = sprintf($this->language->get('error_custom_field'), $custom_field['name']);
				}
			}
		}

		if (!isset($json['error']) && empty($json['error'])) {

			$customer_id = $this->model_account_customer->addCustomer($data);

			//Liqn 尝试绑定微信
			if(isset($this->session->data['weixin_login_openid'])) {
				$this->model_account_customer->saveWxOpenid($customer_id, $this->session->data['weixin_login_openid']);
			}
			if(isset($this->session->data['weixin_avatar'])) {
				//保存到统一的upload数据表
				// $file_name = 'avatar_' . $customer_id . '.' . token(32) . '.jpg';
	   //    $file_path = DIR_UPLOAD . $file_name;
	   //    copy($this->session->data['weixin_avatar'], $file_path);
	   //    $this->load->model('tool/upload');
	   //    $code = $this->model_tool_upload->addUpload($file_name, $file_name);
	   //    //保存code到customer表
	   //    $this->model_account_customer->saveAvatar($customer_id, $code);
	      
	      $code = $this->session->data['weixin_avatar'];
				$this->model_account_customer->saveAvatar($customer_id, $code);	      
			}

			$this->session->data['account'] = 'register';

			$this->load->model('account/customer_group');

			$customer_group_info = $this->model_account_customer_group->getCustomerGroup($customer_group_id);

			if ($customer_group_info && !$customer_group_info['approval']) {
				

				$this->customer->login($data['telephone'], $data['password']);
				


				$data['session_id'] = session_id();
				unset($data['password']);
				unset($data['confirm']);
				unset($data['agree']);
				$json['data'] = $data;

				// Default Payment Address
				$this->load->model('account/address');

				$this->session->data['payment_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());

				if (!empty($data['shipping_address'])) {
					$this->session->data['shipping_address'] = $this->model_account_address->getAddress($this->customer->getAddressId());
				}
			} 

			unset($this->session->data['guest']);
			unset($this->session->data['shipping_method']);
			unset($this->session->data['shipping_methods']);
			unset($this->session->data['payment_method']);
			unset($this->session->data['payment_methods']);

			// Add to activity log
			$this->load->model('account/activity');

			$activity_data = array(
				'customer_id' => $customer_id,
				'name'        => $data['telephone']
			);

			$this->model_account_activity->addActivity('register', $activity_data);

			//给用户注册易极付会员
			 $this->addYijiVip($data['telephone']);

		} else{
			$json['success'] = false;
		}

		if ($this->debugIt) {
			echo '<pre>';
			print_r($json);
			echo '</pre>';
		} else {
			$this->response->setOutput(json_encode($json));
		}
	}

	/*
	* GUEST FUNCTIONS
	*/	
	public function register() {

		$this->checkPlugin();

		if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){
			//add customer
			$requestjson = file_get_contents('php://input');
		
			$requestjson = json_decode($requestjson, true);           

			if (!empty($requestjson)) {
				$this->registerCustomer($requestjson);
			}else {
				$this->response->setOutput(json_encode(array('success' => false)));
			}
		}else {
				$json["error"]		= "Only POST request method allowed";
				$json["success"]	= false;

				$this->response->setOutput(json_encode($json));
		}    
    }

	// 添加易极付会员
	public function addYijiVip($telephone){
		$this->load->model('payment/yiji_register');
		$user_id = $this->model_payment_yiji_register->getUserId($telephone);

		$this->load->model('account/customer');
		$this->model_account_customer->saveVip($telephone,$user_id);
		return;
	}

}